const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
const Md5 = require('md5')
const UserModel = require('./model/user')
//配置第三方中间件 获取post提交过来的数据
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
    UserModel.find({}, (err, doc) => {
        if (err) {
            console.log(err)
            return
        }

        res.send(doc)
    })
})


app.post('/doLogin', (req, res) => {
    var body = req.body;
    console.log(body);
    let username = body.username
    let password = Md5(body.password)
    console.log(username, password)
    UserModel.findOne({ username, password }, (err, doc) => {
        if (err) {
            console.log(err);
            res.send(err)
            return
        }

        console.log(doc)
        res.send(doc)

    })
})
app.post('/doRegister', (req, res) => {
    var body = req.body;
    console.log(body);
    let username = body.username
    let password = Md5(body.password)

    var user = new UserModel({
        username,
        password,
    })
    user.save((err, doc) => {
        if (err) {
            console.log(err)
            return
        }
        console.log('添加成功');
        res.send(doc)
    })
})

app.listen(port, () => console.log(`正在运行 http://127.0.0.1:${port} `))